<template>
  <div style="display: inline-block;min-width: 100%">
    <div class="search-bar">
      <Row>
        <Col span="12">
          <Menu mode="horizontal" @on-select="tabSelect" active-name="electric">
            <MenuItem name="water">
              <i class="monitor icon-water"></i>
              <span>压缩空气</span>
            </MenuItem>
          </Menu>
          <span class="line"></span>
        </Col>
        <Col span="12">
          <div style="float: right;margin-right: 10px;">
            <Form label-position="right" ref="formCustom" :model="overviewForm" :label-width="80">
          <FormItem label="时间：" prop="dateTimeValue" style="margin:9px 0px 0px 0px;" class="form-label">
            <!--<Date-picker type="datetime" format="yyyy-MM-dd HH:mm" placeholder="请选择时间"-->
            <!--style="width: 350px"></Date-picker>-->
            <Cascader :data="DateInit"   :clearable="false" change-on-select :load-data="ttrees" :render-format="format" style="width:200px;top: 100px;" v-model="selectDate" @on-change="changeDate"
                      ></Cascader>
          </FormItem>
            </Form>
          </div>
          <div style="float: right;margin-right: 10px;">
            <label style="margin:9px 0px 0px 0px;">空间：</label>
            <Select v-model="params.factory" style="width:200px" @on-change="factoryChange">
              <Option v-for="item in spaceList" :value="item.label" :key="item.id">{{ item.label }}</Option>
            </Select>
          </div>
        </Col>
      </Row>
    </div>
    <div class="picture">
      <div class="qunee" id="canvasff"></div>
      <Spin size="large" fix v-if="loadImgDatasStatus"></Spin>
    </div>
  </div>
</template>

<script>
  import {DataCardNode} from '../../../static/qunee/cardNode'
  import {formatDate} from '../../../static/qunee/dates'
  export default {
    name: 'AirMeter',
    mounted: function () {
      this.loadFactoryList()
      this.initGraph()
    },
    created () {
      this.init()
    },
    data () {
      return {
        DateInit: [],
        selectDate: [],        //日期三级联动的时间（格式为数组）
        activeDate: formatDate(new Date(), 'yyyy'),
        rootNode: null,
        timers: [],
        expandNodeId: null,
        loadImgDatasStatus: false,
        graph: null,
        layouter: null,
        tree: [],
        tabActive: 'electric',
        spaceList: [],
        eneryTypeMap: {
          water: '水',
          water2: '中水',
          electric: '电',
          coolFlow: '冷量',
          gas: '燃气',
          stream: '蒸汽',
          compressionAir: '压缩空气'
        },
        overviewForm: {
          spaceValue: [4],
        },
        params: {
          type: '压缩空气',
          factory: '',
          times: ''
        }
      }
    },
    methods: {
      init () {
        let self = this
        self.selectDate.push(new Date().format('yyyy'))
        self.yearCalculation(2015, 15)
        self.ensTree(function () {
          self.refreshData()
        })
      },
      ensTree: function (cb) {
        let self = this
        window.myapi.ensTree({type: '成本', factory: 'ZZ', selectDate: this.activeDate}).then(function (res) {
          if (res.data.status === 200) {
            self.ensTreeData = res.data.data

            // let obj = self.getSelectNodesValueString(self.ensTreeData)
            // self.workSpaceString = obj.nodesStr
            // self.$set(self.overviewForm, "spaceValue", obj.nodesNumArr)
            self.workSpaceString = self.ensTreeData[0].label
            self.$set(self.overviewForm, "spaceValue", [self.ensTreeData[0].value])
            cb()
            // self.carbon_allin_list = res.data.data
          } else {

          }
        }).catch(function (e) {
          console.log(e)
        })
      },
      refreshData () {
        let self = this
      },
      yearCalculation: function (initYear, number) {
        let self = this
        for (let i = 0; i <= number; i++) {
          let obj = {}
          obj.value = initYear + i
          obj.value = obj.value.toString()
          obj.label = initYear + i + '年'
          obj.children = []
          obj.loading = false
          self.DateInit.push(obj)
        }
      },
      //年份获取月份和天
      ttrees: function (item, callback) {
        item.loading = true
        window.myapi.ttrees({year: '2019'}).then((res) => {
          if (res.data.status === 200) {
            item.children = res.data.data[0].children
            item.loading = false
            callback()
          }
        }).catch(function (e) {
          console.log(e)
        })
      },
      // 时间改变-----具体时间/今日/本月/今年
      changeDate: function (Datetime) {
        let self = this
        if (typeof (Datetime) == 'string') {
          self.activeDate = Datetime
          self.selectDate = Datetime.split('-')
        } else {
          self.activeDate = Datetime.join('-')
        }
        self.activeDateBtn = ''
        self.refreshData()
      },
      format (labels, selectedData) {
        let str = ''
        for (let i = 0; i < selectedData.length; i++) {
          if (!i) {
            str = selectedData[i].value
          } else {
            str = str + ' - ' + selectedData[i].value
          }
        }
        return str
      },

      loadFactoryList: function () {
        let getData = {
          'size': 100,
          'page': 0,
          type_lte: 2
        }
        window.myapi.space_list(getData).then(res => {
          if (res.data.status === 200) {
            if (res.data.data.content.length === 0) {
              this.$Message.info('查询无工厂数据，请检测空间数据或是否设置了工厂层级')
              return
            }
            this.spaceList = res.data.data.content
            // this.params.factory = this.spaceList[0].label
            // 郑州项目暂指定郑州工厂为默认的工厂
            this.params.factory = 'ZZ'
            this.loadTreeDatas()
          } else {
            let msg = res.data.msg ? res.data.msg : '请求数据失败!'
            this.$Message.error({content: msg, duration: 5, closable: true})
          }
        }).catch(function (e) {
        })
      },
      initGraph: function () {
        // 初始化 拓扑图33
        if (this.graph === null) {
          this.graph = new Q.Graph('canvasff')
          // 禁止双击 放大
          this.graph.enableDoubleClickToOverview = false
          // 设置提示贴
          // this.graph.enableTooltip = false
          // this.graph.tooltipDelay = 0
          // this.graph.tooltipDuration = 100000
          // 只读
          // this.graph.interactionMode = Q.Consts.INTERACTION_MODE_VIEW
          // 添加 一些事件
          // this.graph.addCustomInteraction(this.events)
          // 添加一些样式
          // 默认样式，禁止点击效果
          this.graph.styles = {}
          this.graph.styles[Q.Styles.SELECTION_BORDER] = 0
          this.graph.styles[Q.Styles.SELECTION_SHADOW_BLUR] = 0
          this.graph.styles[Q.Styles.SELECTION_COLOR] = '#0005ff63'
          // 添加动画
          if (this.layouter === null) {
            this.layouter = new Q.TreeLayouter(this.graph)
            // this.layouter.layoutType = Q.Consts.LAYOUT_TYPE_EVEN_VERTICAL
            // layouter.hGap = 100;
            this.layouter.vGap = 10
          }
          this.graph.addCustomInteraction({
            onmousemove: (evt, graph) => {
              let data = evt.getData()
              if (!data) {
                return
              }
              let target = graph.hitTest(evt)
              if (target && target.name === 'handler') {
                graph.cursor = 'pointer'
                return
              }
              graph.cursor = null
            }
          })

          this.graph.onclick = (evt) => {
            let data = evt.getData()
            if (!data) {
              return
            }
            let target = this.graph.hitTest(evt)
            if (target && target.name === 'handler') {
              // 点击展开的 按钮，标记333
              data.reverseExpanded()
              this.layouter.doLayout({
                callback: () => {
                  // 这个必须移动，否则，线条指向错乱
                  this.moveNodes(200)
                }
              })

              // 只能显示一个支点控制
              if (this.expandNodeId == null) {
                this.expandNodeId = data.id
              } else {
                if (data.expandChildren) {
                  if (this.expandNodeId !== data.id) {
                    this.graph.graphModel.getById(this.expandNodeId).expandChildren = false
                    this.expandNodeId = data.id
                  }
                } else {
                  this.expandNodeId = null
                }
              }
            }
          }
        }
      },
      cleanGraph: function () {
        this.tree = []
        this.graph.clear()
        this.stopTimers()
      },
      createNode (fromNode, nodeData, edgeType) {
        let node = new DataCardNode(nodeData.name, nodeData.id, Q.Graphs.exchanger2)
        node.setStyle(Q.Styles.LABEL_VISIBLE, false)
        node.set('level', nodeData.level)
        // 间距调整116666
        if (nodeData.level <= 1) {
          node.hGap = 400
          node.vGap = 200
        } else {
          node.hGap = 30
          node.vGap = 20
        }
        this.graph.addElement(node)
        if (fromNode) {
          node.parent = node.host = fromNode
          node.name = fromNode.name + '-' + node.name
          this.createEdge(fromNode, node, edgeType)
        }

        return node
      },
      createEdge (from, to, edgeType) {
        let edge = this.graph.createEdge(from, to)
        edge.edgeType = edgeType || Q.Consts.EDGE_TYPE_ORTHOGONAL_VERTICAL
        // 线条样式
        edge.setStyle(Q.Styles.EDGE_SPLIT_BY_PERCENT, false)
        edge.setStyle(Q.Styles.EDGE_SPLIT_VALUE, 30)
        // edge.setStyle(Q.Styles.EDGE_COLOR, '#2898E0')
        // edge.setStyle(Q.Styles.EDGE_WIDTH, 3)
        // 禁止圆角
        // edge.setStyle(Q.Styles.EDGE_CORNER, Q.Consts.EDGE_CORNER_NONE)
        // edge.setStyle(Q.Styles.EDGE_TO_OFFSET, 20)
        return edge
      },
      generateRouterPath: function () {
        if (this.graph == null) {
          this.initGraph()
        }
       // 创建顶级点
        let root = this.createNode(null, this.tree[0], null)
        this.rootNode = root
        root.layoutType = Q.Consts.LAYOUT_TYPE_EVEN_HORIZONTAL
        // 关联数据
        this.fuckRelation(root, this.tree[0])
        // 递归创建子孙节点
        this.makeSonNodes(root, this.tree[0])
        this.doLayout()
        this.startTimers()
      },
      makeSonNodes (fatherNode, fatherData) {

        let children = fatherData.children
        let edgeType = Q.Consts.EDGE_TYPE_VERTICAL_HORIZONTAL
        for (let i = 0; i < children.length; i++) {
            // 创建节点
          let sonData = children[i]
          let sonNode = null
          if (fatherData.level === 1) {
             sonNode = this.createNode(fatherNode, sonData, null)
          } else {
            sonNode = this.createNode(fatherNode, sonData, edgeType)
          }
          sonNode.parentChildrenDirection = Q.Consts.DIRECTION_BOTTOM
          sonNode.layoutType = Q.Consts.LAYOUT_TYPE_EVEN_VERTICAL

          // 是否展开 啊时代发生的发
          if (fatherData.level >= 3) {
            fatherNode.expandChildren = false
          }

          // 关联数据
          this.fuckRelation(sonNode, sonData)

          if (sonData.children.length > 0) {
            this.makeSonNodes(sonNode, sonData)
          }
        }
      },
      fuckRelation: function (node, source) {
        // 关联属性的数据配置
        if (source.props.length === 0) {
          return
        }
        let targetProps = source.props.filter(sour => {
          return sour.type === 1
        })

        if (targetProps.length > 0) {
          let firstProp = targetProps[0]
          node.set('did', firstProp.devId)
          if (firstProp.proName) {
            node.set('key1', firstProp.proName)
          } else {
            // node.set('key1', '未配置')
          }

          if (targetProps.length > 1) {
            let secondProp = targetProps[1]
            if (secondProp.proName) {
              node.set('key2', secondProp.proName)
            } else {
              // node.set('key2', '未配置')
            }
          }
        }
      },
      startTimers () {
        // 启动请求数据
        this.graph.forEach(node => {
          if (node instanceof DataCardNode) {
            if (node.get('key1') && node.get('did')) {
              this.timers.push(setInterval(() => {
                this.requestRealData(node, {devId: node.get('did'), dataType: node.get('key1')}, 1)
              }, 2700 + Math.floor(Math.random() * 500)))
            }
            if (node.get('key2') && node.get('did')) {
              this.timers.push(setInterval(() => {
                this.requestRealData(node, {devId: node.get('did'), dataType: node.get('key2')}, 2)
              }, 2700 + Math.floor(Math.random() * 500)))
            }
          }
        })
      },
      stopTimers () {
        if (this.timers.length !== 0) {
          this.timers.forEach(item => window.clearInterval(item))
        }
      },
      formatNumber (number, decimal) {
        return number.toFixed(decimal)
      },
      requestRealData (node, param, index) {
        // 请求数据执行体
        window.myapi.do_post('iot/dev/proReal', param).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            if (resp.status === 200 && resp.data.status === 200) {
              let resultss = resp.data.data
              node.set('property' + index, resultss.value + '')
              node.set('unit' + index, resultss.unit + '')
            }
          } else {
            this.$Notice.error({
              title: '通知',
              desc: resp.data.msg
            })
          }
        }).catch(error => {
        }).finally(() => {
        })
      },
      doLayout () {
        this.layouter.doLayout({
          callback: () => {
            this.moveNodes(200)
            // this.graph.moveToCenter()
            // this.graph.zoomToOverview()
            let wh = this.rootNode
            this.graph.centerTo(wh.location.x, 450, 1)
          }
        })
      },
      moveNodes (dx) {
        // 位移问题  导致 纵横布局不能太短，不能展开
        let rightBound = 0
        let testX = 0
        let testName
        let prevElement
        this.graph.graphModel.forEachByTopoBreadthFirstSearch(element => {
          if (element instanceof Q.Node && element.get('level') > 2) {
            // 3 级开始才位移
            // 每次移动，整个父子节点链的线条都会移动
            this.graph.moveElements([element], dx, 0)

            if (!element.parent) {
              rightBound = testX + this.graph.getUIBounds(element).width
              if (element.x < rightBound) {
                this.graph.moveElements([element], rightBound - element.x, 0)
              }
              if (prevElement && !prevElement.hasChildren()) {
                this.graph.moveElements([element], dx, 0)
              }
              prevElement = element
            }

            if (element.x >= testX) {
              testX = element.x
              testName = element.name
            }
          }
        })
      },
      loadTreeDatas () {
        this.params.times = this.activeDate
        this.cleanGraph()
        this.loadImgDatasStatus = true
        this.expandNodeId = null
        window.myapi.do_post('ens/tree', this.params).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            this.tree = resp.data.data
            if (this.tree.length > 0) {
              // 生成路线图
              this.generateRouterPath()
            } else {
              this.$Notice.info({
                title: '提示',
                desc: '该空间没有配置数据，无图示可显示'
              })
            }
          } else {
            this.$Notice.error({
              title: '通知',
              desc: resp.data.msg
            })
          }
        }).catch(error => {
        }).finally(() => {
          this.loadImgDatasStatus = false
        })
      },
      getSpaceList: function () {
        this.spaceList = this.$store.state.user.spaces[0].children
        this.params.factory = this.spaceList[0].label
      },
      factoryChange (index) {
        this.loadTreeDatas()
      },
      tabSelect (e) {
        this.tabActive = e
        this.params.type = this.eneryTypeMap[e]
        this.loadTreeDatas()
      }
    },
    beforeDestroy: function () {
      this.stopTimers()
    }
  }
</script>

<style scoped>

  ul, li {
    margin: 0;
    list-style: none;
  }

  .search-bar {
    height: 50px;
    line-height: 50px;
    background: #fff;
    border-bottom: solid 1px #ede8e8ab;
  }

  .ivu-menu-horizontal.ivu-menu-light:after {
    background: none;
  }

  .ivu-menu-item {
    font-size: 18px;
    padding: 0 5px;
    margin: 0 15px;
  }

  .ivu-menu-light.ivu-menu-horizontal .ivu-menu-item-active, .ivu-menu-light.ivu-menu-horizontal .ivu-menu-submenu-active, .ivu-menu-light.ivu-menu-horizontal .ivu-menu-item:hover, .ivu-menu-light.ivu-menu-horizontal .ivu-menu-submenu:hover {
    border-bottom-width: 4px;
    color: #4e78fe;
    border-color: #4e78fe;
  }

  .ivu-menu-horizontal {
    height: 40px;
    line-height: 40px;
    vertical-align: middle;
    display: inline-block;
  }

  .form-label {
    font-size: 14px;
    color: #363636;
    vertical-align: middle;
    margin-left: 32px;
  }

  /*.line {*/
    /*height: 48px;*/
    /*width: 1px;*/
    /*display: inline-block;*/
    /*vertical-align: middle;*/
    /*margin-left: 28px;*/
    /*background: #d6dbe3;*/
  /*}*/

  .picture {
    width: 99%;
    /*padding: 5px;*/
    margin: 0px 5px;
  }

  /*2k*/
  @media screen and (min-width: 1921px) {
    .picture {
      height: 1190px
    }
  }

  /* css注释：设置了浏览器宽度不小于1201px时 abc 显示1200px宽度 */
  @media screen and (max-width: 1920px) {
    .picture {
      height: 930px;
    }
  }
  .qunee{
    position: absolute;
    width: 99%;
    top: 110px;
    bottom: 10px;
  }
</style>
